package com.bayi.storage.base

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.MotionEvent
import android.view.View
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.bayi.storage.utils.ToastUtil
import com.bayi.storage.utils.Utils
import com.lky.toucheffectsmodule.factory.TouchEffectsFactory
import java.lang.reflect.ParameterizedType

/**
 * @author Administrator on 2024-05-31.
 * <p>
 * 站在顶峰 看世界
 * 落到谷底 思人生
 */
abstract class BaseActivity<VM : BaseViewModel, VB : ViewDataBinding> :
    AppCompatActivity() {

    lateinit var binding: VB

    lateinit var mViewModel: VM


    override fun onCreate(savedInstanceState: Bundle?) {
        TouchEffectsFactory.initTouchEffects(this)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        binding = createViewBinding()
        binding.lifecycleOwner = this
        setContentView(binding.root)

        //获得泛型参数的实际类型
        val vmClass =
            (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
        mViewModel = ViewModelProvider(this).get(vmClass)

        initView()

    }

    protected abstract fun createViewBinding(): VB
    protected abstract fun initView()


    /**
     * 申请权限
     */
    private fun requestPermissions() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // 先判断有没有权限
                if (!Environment.isExternalStorageManager()) {
                    val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                    intent.data = Uri.parse("package:$packageName")
                    startActivityForResult(intent, 0x0020)
                } else {
                    aPermissions()
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                aPermissions()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions!!, grantResults)
        if (requestCode == 0x0010) { // If request is cancelled, the result arrays are empty.
            if (grantResults.size > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED
            ) {
//                startActivity(Intent(this, MainLandscapeActivity::class.java))
//                finish()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0x0020 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                aPermissions()
            } else {
                ToastUtil.show("存储权限获取失败")
            }
        }
    }

    private fun aPermissions() {
        ActivityCompat.requestPermissions(
            this, arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.LOCATION_HARDWARE,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_FINE_LOCATION
            ), 0x0010
        )
    }


    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        setHideStateBarNavigation()
    }

    private fun setHideStateBarNavigation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 全屏显示，隐藏状态栏和导航栏，拉出状态栏和导航栏显示一会儿后消失。
            window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                // 判断连续点击事件时间差
                if (!allowMultiClick() && isFastClick()) {
                    return true
                }
                //关闭输入法
                Utils.hideSoftInputFromWindow(window)
//                ResetSingle.getInstance().restTime()
            }
            MotionEvent.ACTION_MOVE -> {}
            MotionEvent.ACTION_UP -> {}
            else -> {}
        }
        return super.dispatchTouchEvent(ev)
    }


    /**
     * 是否允许多次点击
     *
     * @return 默认false，子类可以重写
     */
    open fun allowMultiClick(): Boolean {
        return false
    }

    private var LAST_CLICK_TIME // 上一次点击事件
            : Long = 0

    private fun isFastClick(): Boolean {
        var flag = true
        val currentClickTime = System.currentTimeMillis()
        // 两次点击间隔不能少于500ms
        if (currentClickTime - LAST_CLICK_TIME >= 300) {
            flag = false
        }
        LAST_CLICK_TIME = currentClickTime
        return flag
    }
}